﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using PasteLoggerBoard.redismodel;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace PasteLoggerBoard.serilogmodels
{
    /// <summary>
    ///
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "root", "root" })]
    public class AppInfoAppService : IUserAppService
    {

        /// <summary>
        /// 
        /// </summary>
        private readonly IPasteLoggerBoardDbContext _dbContext;

        /// <summary>
        /// 
        /// </summary>
        private RabbitMQProducer _rabbitmqProducer => LazyServiceProvider.LazyGetRequiredService<RabbitMQProducer>();

        private IOptions<RabbitConfig> config => LazyServiceProvider.LazyGetRequiredService<IOptions<RabbitConfig>>();

        private IAppCache _appCache => LazyServiceProvider.LazyGetRequiredService<IAppCache>();

        /// <summary>
        ///
        ///</summary>
        ///<param name="dbContext"></param>
        public AppInfoAppService(IPasteLoggerBoardDbContext dbContext) : base()
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 按页获取
        ///</summary>
        ///<param name="input">页大小</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PagedResultDto<AppInfoListDto>> GetListAsync(InputSearchBase input)
        {

            var query = _dbContext.AppInfo.Where(t => 1 == 1).OrderByDescending(xy => xy.Id);
            var _pagedto = new PagedResultDto<AppInfoListDto>();
            if (input.page == 1)
            {
                _pagedto.TotalCount = await query.CountAsync();
            }
            var userList = await query.Page(input.page, input.size).ToListAsync();
            var temList = ObjectMapper.Map<List<AppInfo>, List<AppInfoListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }

        /// <summary>
        /// 按页获取
        ///</summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<AppInfoListDto>> Options()
        {

            var query = await _dbContext.AppInfo.Where(t => true).OrderBy(x => x.Sort).AsNoTracking().ToListAsync();
            var temList = ObjectMapper.Map<List<AppInfo>, List<AppInfoListDto>>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取单项
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public AppInfoDto GetByIdAsync(int id)
        {
            var query = _dbContext.AppInfo.Where(t => t.Id == id).AsNoTracking().FirstOrDefault();
            if (query == null || query == default)
            {
                throw new PasteLoggerBoardException("没有找到这样的信息", 404);
            }
            var temList = ObjectMapper.Map<AppInfo, AppInfoDto>(query);
            //if (!String.IsNullOrEmpty(query.InfoFilterRoute))
            //{
            //    var _lines = query.InfoFilterRoute.Split(";");
            //    temList.InfoFilterRoute = String.Join("\r\n", _lines);
            //}
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public AppInfoUpdateDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.AppInfo.Where(t => t.Id == id).AsNoTracking().FirstOrDefault();
            if (query == null || query == default)
            {
                throw new PasteLoggerBoardException("没有找到这样的信息", 404);
            }
            var temList = ObjectMapper.Map<AppInfo, AppInfoUpdateDto>(query);
            //if (!String.IsNullOrEmpty(query.InfoFilterRoute))
            //{
            //    var _lines = query.InfoFilterRoute.Split(";");
            //    temList.InfoFilterRoute = String.Join("\r\n", _lines);
            //}
            return temList;
        }


        /// <summary>
        /// 添加一个
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> CreateItemAsync(AppInfoAddDto input)
        {
            var _userid = base.ReadCurrentUserId();
            var info = ObjectMapper.Map<AppInfoAddDto, AppInfo>(input);
            //添加自定义
            _dbContext.Add(info);
            //var _route_lines = "";
            //if (!String.IsNullOrEmpty(input.InfoFilterRoute))
            //{
            //    var lines = input.InfoFilterRoute.SplitToLines();
            //    _route_lines = string.Join(";", lines);
            //}
            //info.InfoFilterRoute = _route_lines;
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<AppInfo, AppInfoDto>(info);

            //var _model = new LoggerModel
            //{
            //    Exception = "",
            //    Level = "appdto",
            //    MessageTemplate = "",
            //    Properties = null,
            //    Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            //};
            //var _appjson = new JObject { };
            //_appjson.Add("AppName", "UNKNOW");
            //_model.Properties = _appjson;
            //_model.MessageTemplate = Newtonsoft.Json.JsonConvert.SerializeObject(backinfo);
            //var _config = config.Value;
            //await _rabbitmqProducer.SendAsync(_config.Exchange, Newtonsoft.Json.JsonConvert.SerializeObject(_model), "log.setting");

            var _result = await _appCache.PublishAsync("serilog:appdto", Newtonsoft.Json.JsonConvert.SerializeObject(backinfo));

            return $"推送给{_result}个订阅者";
        }
        /// <summary>
        /// 更新一个
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> UpdateItemAsync(AppInfoUpdateDto input)
        {
            var info = await _dbContext.AppInfo.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }
            ObjectMapper.Map<AppInfoUpdateDto, AppInfo>(input, info);
            //var _route_lines = "";
            //if (!String.IsNullOrEmpty(input.InfoFilterRoute))
            //{
            //    var lines = input.InfoFilterRoute.SplitToLines();
            //    _route_lines = string.Join(";", lines);
            //}
            //info.InfoFilterRoute = _route_lines;
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<AppInfo, AppInfoDto>(info);

            //var _model = new LoggerModel
            //{
            //    Exception = "",
            //    Level = "appdto",
            //    MessageTemplate = "",
            //    Properties = null,
            //    Timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            //};
            ////var _app = new { AppName="Unknow" };
            //var _appjson = new JObject { };
            //_appjson.Add("AppName", "UNKNOW");
            //_model.Properties = _appjson;
            //_model.MessageTemplate = Newtonsoft.Json.JsonConvert.SerializeObject(backinfo);
            //var _config = config.Value;
            //await _rabbitmqProducer.SendAsync(_config.Exchange, Newtonsoft.Json.JsonConvert.SerializeObject(_model), "log.setting");

            var _result = await _appCache.PublishAsync("serilog:appdto", Newtonsoft.Json.JsonConvert.SerializeObject(backinfo));

            return $"推送给{_result}个订阅者";
        }
    }
}
